import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from service.utils import logger
from retrying import retry


@retry(stop_max_attempt_number=3, wait_fixed=1000)
def send_email(qq_email, auth_code, recipient, subject, content, file_path=None):
    """
    使用QQ邮箱发送带Excel附件的邮件
    :param qq_email: 发件人QQ邮箱
    :param auth_code: QQ邮箱授权码
    :param recipient: 收件人邮箱
    :param subject: 邮件主题
    :param content: 邮件正文内容
    :param excel_path: Excel文件路径
    """
    # 创建邮件对象
    msg = MIMEMultipart()
    msg["From"] = qq_email
    msg["To"] = recipient
    msg["Subject"] = subject

    # 添加邮件正文
    msg.attach(MIMEText(content, "plain", "utf-8"))

    # 添加Excel附件
    if file_path is not None:
        with open(file_path, "rb") as f:
            file = MIMEApplication(f.read())
            file.add_header(
                "Content-Disposition", "attachment", filename=file_path.split("/")[-1]
            )
            msg.attach(file)

    # 发送邮件
    server = smtplib.SMTP_SSL("smtp.qq.com", 465)
    server.login(qq_email, auth_code)
    server.sendmail(qq_email, recipient, msg.as_string())
    server.quit()
    logger.info("邮件发送成功")
